// 存储拦截到的视频URL
let videoUrls = new Map();

// 监听消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    console.log('Background收到消息:', request);
    
    if (request.action === 'DOWNLOAD_VIDEO') {
        console.log('准备下载视频:', request.url);
        
        // 异步处理下载
        (async () => {
            try {
                // 先检查URL内容类型和重定向
                console.log('检查URL内容类型:', request.url);
                const response = await fetch(request.url, { method: 'HEAD' });
                const contentType = response.headers.get('content-type');
                const contentLength = response.headers.get('content-length');
                const finalUrl = response.url;
                
                console.log('Content-Type:', contentType);
                console.log('Content-Length:', contentLength);
                console.log('Final URL:', finalUrl);
                
                // 检查是否为视频文件
                if (contentType) {
                    if (contentType.includes('text/') || contentType.includes('application/javascript') || contentType.includes('application/json')) {
                        console.error('URL指向的不是视频文件:', contentType);
                        sendResponse({
                            success: false,
                            error: `URL指向的不是视频文件，内容类型: ${contentType}`,
                            contentType: contentType
                        });
                        return;
                    }
                }
                
                // 根据内容类型确定文件扩展名
                let extension = '.mp4'; // 默认扩展名
                if (contentType) {
                    if (contentType.includes('video/mp4')) extension = '.mp4';
                    else if (contentType.includes('video/webm')) extension = '.webm';
                    else if (contentType.includes('video/avi')) extension = '.avi';
                    else if (contentType.includes('video/mov')) extension = '.mov';
                    else if (contentType.includes('video/flv')) extension = '.flv';
                    else if (contentType.includes('video/3gpp')) extension = '.3gp';
                    else if (contentType.includes('video/quicktime')) extension = '.mov';
                    else if (contentType.includes('application/octet-stream')) {
                        // 根据URL推断扩展名
                        if (finalUrl.includes('.mp4')) extension = '.mp4';
                        else if (finalUrl.includes('.webm')) extension = '.webm';
                        else if (finalUrl.includes('.avi')) extension = '.avi';
                        else if (finalUrl.includes('.mov')) extension = '.mov';
                        else if (finalUrl.includes('.flv')) extension = '.flv';
                    }
                }
                
                // 生成文件名
                const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
                const fileName = `${request.filename || '抖音视频'}_${timestamp}${extension}`;
                
                console.log('开始下载，文件名:', fileName);
                
                // 执行下载
                const downloadId = await chrome.downloads.download({
                    url: finalUrl,
                    filename: fileName,
                    saveAs: false
                });
                
                console.log('下载已开始，ID:', downloadId);
                
                sendResponse({
                    success: true,
                    downloadId: downloadId,
                    fileName: fileName,
                    contentType: contentType,
                    finalUrl: finalUrl
                });
                
            } catch (error) {
                console.error('下载过程中出错:', error);
                let errorMessage = '下载失败';
                
                if (error.message.includes('network')) {
                    errorMessage = '网络连接失败，请检查网络';
                } else if (error.message.includes('permission')) {
                    errorMessage = '权限不足，请检查下载权限';
                } else if (error.message.includes('cors')) {
                    errorMessage = 'CORS错误，无法访问该URL';
                } else if (error.message.includes('fetch')) {
                    errorMessage = '无法获取文件信息，URL可能无效';
                } else {
                    errorMessage = `下载失败: ${error.message}`;
                }
                
                console.error('详细错误信息:', errorMessage);
                sendResponse({
                    success: false,
                    error: errorMessage
                });
            }
        })();
        
        return true; // 保持消息通道开放
    }
    
    if (request.type === "DOWNLOAD_VIDEO") {
        console.log('收到下载请求:', request);
        console.log('URL详细信息:', {
            url: request.url,
            type: typeof request.url,
            length: request.url ? request.url.length : 0,
            startsWithHttp: request.url ? request.url.startsWith('http') : false,
            startsWithHttps: request.url ? request.url.startsWith('https://') : false
        });
        
        if (!request.url || (!request.url.startsWith('https://') && !request.url.startsWith('http://'))) {
            console.error('无效的视频URL:', request.url);
            sendResponse({ success: false, error: 'Invalid video URL' });
            return true;
        }

        // 清理文件名
        const fileName = (request.filename || request.title || 'douyin_video')
            .replace(/[<>:"/\\|?*]/g, '')
            .replace(/\s+/g, '_')
            .substring(0, 100) + '.mp4';

        console.log('开始下载文件:', fileName);
        console.log('下载URL:', request.url);

        // 检查URL是否有效
        try {
            const urlObj = new URL(request.url);
            console.log('URL解析成功:', urlObj.href);
        } catch (e) {
            console.error('URL格式无效:', e);
            sendResponse({ success: false, error: 'Invalid URL format: ' + e.message });
            return true;
        }

        // 检查URL内容类型
        console.log('Background: 检查URL内容类型...');
        fetch(request.url, { method: 'HEAD' })
            .then(response => {
                const contentType = response.headers.get('content-type');
                const contentLength = response.headers.get('content-length');
                
                console.log('Background: Content-Type:', contentType);
                console.log('Background: Content-Length:', contentLength);
                console.log('Background: Response URL:', response.url);
                
                // 如果响应URL不同，说明发生了重定向
                let finalUrl = request.url;
                if (response.url !== request.url) {
                    console.log('Background: 检测到重定向，使用新URL:', response.url);
                    finalUrl = response.url;
                }
                
                // 检查内容类型
                if (contentType) {
                    if (contentType.includes('text/') || contentType.includes('application/javascript')) {
                        console.error('Background: URL指向的不是视频文件，而是:', contentType);
                        sendResponse({ 
                            success: false, 
                            error: `URL指向的不是视频文件，内容类型: ${contentType}`,
                            details: { contentType, url: finalUrl }
                        });
                        return;
                    }
                    
                    if (!contentType.includes('video/') && !contentType.includes('application/octet-stream')) {
                        console.warn('Background: 内容类型可能不是视频:', contentType);
                    }
                }
                
                // 根据内容类型确定扩展名
                let extension = '.mp4';
                if (contentType) {
                    if (contentType.includes('video/mp4')) extension = '.mp4';
                    else if (contentType.includes('video/webm')) extension = '.webm';
                    else if (contentType.includes('video/avi')) extension = '.avi';
                    else if (contentType.includes('video/mov')) extension = '.mov';
                    else if (contentType.includes('application/vnd.apple.mpegurl') || finalUrl.includes('.m3u8')) extension = '.m3u8';
                }
                
                // 更新文件名扩展名
                let finalFileName = fileName;
                if (!finalFileName.includes('.')) {
                    finalFileName += extension;
                } else {
                    // 替换现有扩展名
                    finalFileName = finalFileName.replace(/\.[^.]+$/, extension);
                }

                console.log('Background: 准备下载文件:', finalFileName);
                console.log('Background: 最终下载URL:', finalUrl);

                chrome.downloads.download({
                    url: finalUrl,
                    filename: finalFileName,
                    saveAs: false,
                    conflictAction: 'uniquify'
                }, (downloadId) => {
                    if (chrome.runtime.lastError) {
                        console.error('Background: 下载失败:', chrome.runtime.lastError);
                        sendResponse({ 
                            success: false, 
                            error: '下载失败: ' + chrome.runtime.lastError.message,
                            details: {
                                url: finalUrl,
                                filename: finalFileName,
                                contentType: contentType,
                                error: chrome.runtime.lastError
                            }
                        });
                    } else {
                        console.log('Background: 下载开始，ID:', downloadId);
                        sendResponse({ 
                            success: true, 
                            downloadId: downloadId,
                            fileName: finalFileName,
                            contentType: contentType
                        });
                    }
                });
            })
            .catch(error => {
                console.error('Background: 检查URL失败:', error);
                // 如果检查失败，仍然尝试下载
                chrome.downloads.download({
                    url: request.url,
                    filename: fileName,
                    saveAs: false,
                    conflictAction: 'uniquify'
                }, (downloadId) => {
                    if (chrome.runtime.lastError) {
                        sendResponse({ 
                            success: false, 
                            error: '下载失败: ' + chrome.runtime.lastError.message
                        });
                    } else {
                        sendResponse({ 
                            success: true, 
                            downloadId: downloadId,
                            fileName: fileName,
                            warning: '无法检查内容类型，可能不是视频文件'
                        });
                    }
                });
            });

        return true;
    }
    
    if (request.type === "GET_VIDEO_URLS") {
        const tabId = sender.tab?.id;
        const urls = tabId ? videoUrls.get(tabId) || [] : [];
        console.log('Background: 请求获取视频URLs，tabId:', tabId);
        console.log('Background: 当前存储的所有URLs:', Array.from(videoUrls.entries()));
        console.log('Background: 返回拦截到的视频URLs:', urls);
        sendResponse({ urls });
        return true;
    }
});

// 视频URL验证函数
function isValidVideoUrl(url) {
    if (!url || typeof url !== 'string') return false;
    
    console.log('Background: 验证URL:', url);
    
    try {
        // 基本URL格式检查
        if (!url.startsWith('http://') && !url.startsWith('https://')) {
            console.log('Background: URL协议验证失败');
            return false;
        }
        
        // 排除明确的非视频内容
        const excludePatterns = [
            '.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg', '.ico',
            '.css', '.js', '.json', '.xml', '.txt', '.html',
            'avatar', 'cover', 'thumbnail', 'data:', 'blob:',
            'recommend/', 'feed/', 'search/', 'comment/', 'user/', 'profile/'
        ];
        
        const lowerUrl = url.toLowerCase();
        for (const pattern of excludePatterns) {
            if (lowerUrl.includes(pattern)) {
                console.log('Background: URL包含排除模式:', pattern);
                return false;
            }
        }
        
        // 检查视频相关域名
        const videoDomains = [
            'douyin.com', 'douyinvod.com', 'douyincdn.com',
            'byteimg.com', 'tos.com', 'tiktokcdn.com', 'muscdn.com',
            'bytedance.com', 'snssdk.com', 'pstatp.com'
        ];
        
        const hasVideoDomain = videoDomains.some(domain => url.includes(domain));
        
        // 检查视频文件扩展名
        const videoExtensions = ['.mp4', '.webm', '.m4v', '.mov', '.avi', '.flv', '.m3u8'];
        const hasVideoExtension = videoExtensions.some(ext => 
            lowerUrl.includes(ext) && (lowerUrl.endsWith(ext) || lowerUrl.includes(ext + '?'))
        );
        
        // 检查视频相关关键字
        const videoKeywords = [
            'video', 'play_addr', 'download_addr', 'video_id', 
            'aweme/v1/play', 'stream', '/play/', '/video/'
        ];
        
        const hasVideoKeyword = videoKeywords.some(keyword => lowerUrl.includes(keyword));
        
        // 检查长ID模式（可能是视频资源）
        const hasLongId = /\/[a-zA-Z0-9_-]{15,}/.test(url);
        
        // 综合判断
        const isValid = (hasVideoDomain && (hasVideoExtension || hasVideoKeyword || hasLongId)) ||
                       hasVideoExtension ||
                       (hasVideoKeyword && url.length > 50);
        
        if (isValid) {
            console.log('Background: URL验证通过 - 域名:', hasVideoDomain, '扩展名:', hasVideoExtension, '关键字:', hasVideoKeyword, '长ID:', hasLongId);
        } else {
            console.log('Background: URL验证失败 - 域名:', hasVideoDomain, '扩展名:', hasVideoExtension, '关键字:', hasVideoKeyword, '长ID:', hasLongId);
        }
        
        return isValid;
    } catch (e) {
        console.log('Background: URL验证出错:', e);
        return false;
    }
}

// 监听网络请求
chrome.webRequest.onBeforeRequest.addListener(
    (details) => {
        const url = details.url;
        console.log('Background: 拦截到请求:', url);
        
        if (isValidVideoUrl(url)) {
            console.log('Background: 保存有效视频URL:', url);
            if (!videoUrls.has(details.tabId)) {
                videoUrls.set(details.tabId, []);
            }
            const urls = videoUrls.get(details.tabId);
            if (!urls.includes(url)) {
                urls.push(url);
                console.log('Background: 当前标签页视频URLs:', urls);
            }
        } else {
            console.log('Background: URL验证失败，不保存:', url);
        }
    },
    {
        urls: [
            "*://*.douyin.com/*",
            "*://*.douyinvod.com/*",
            "*://*.douyincdn.com/*",
            "*://*.bytedance.com/*",
            "*://*.byteimg.com/*",
            "*://*.ixigua.com/*",
            "*://*.tiktok.com/*",
            "*://*.tiktokcdn.com/*",
            "*://*.musical.ly/*",
            "*://*.tos.com/*",
            "*://*.snssdk.com/*",
            "*://*.muscdn.com/*",
            "*://*.pstatp.com/*",
            "*://*.toutiaoapi.com/*",
            "*://*.volcengineapi.com/*"
        ]
    },
    ["requestBody"]
);

// 修改请求头，绕过防盗链
chrome.webRequest.onBeforeSendHeaders.addListener(
    (details) => {
        const headers = details.requestHeaders || [];
        
        // 添加必要的请求头
        headers.push({
            name: 'Referer',
            value: 'https://www.douyin.com/'
        });
        
        headers.push({
            name: 'User-Agent',
            value: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
        });
        
        return { requestHeaders: headers };
    },
    {
        urls: [
            'https://*.douyinvod.com/*',
            'https://*.bytedance.com/*',
            'https://*.douyin.com/*',
            'https://*.snssdk.com/*',
            'https://*.douyincdn.com/*',
            'https://*.pstatp.com/*'
        ]
    },
    ['requestHeaders', 'extraHeaders']
);

// 清理过期的URL
setInterval(() => {
    console.log('清理过期的视频URL缓存');
    videoUrls.clear();
}, 5 * 60 * 1000); // 5分钟清理一次

// 监听标签页关闭，清理对应的URL
chrome.tabs.onRemoved.addListener((tabId) => {
    if (videoUrls.has(tabId)) {
        videoUrls.delete(tabId);
        console.log(`清理标签页 ${tabId} 的视频URL缓存`);
    }
});

// 监听下载状态变化
chrome.downloads.onChanged.addListener((downloadDelta) => {
    console.log('下载状态变化:', downloadDelta);
    
    if (downloadDelta.state) {
        const state = downloadDelta.state.current;
        const downloadId = downloadDelta.id;
        
        if (state === 'complete') {
            console.log(`下载完成，ID: ${downloadId}`);
        } else if (state === 'interrupted') {
            console.error(`下载中断，ID: ${downloadId}`);
        }
    }
});